<template>
  <div class="userPhoto">
    <van-popup :value="userPhoto" position="right">
      <van-nav-bar
        title="修改头像"
        left-text=""
        right-text="保存"
        left-arrow
        @click-left="$emit('input', false)"
        @click-right="onClickRight"
      />
      <van-uploader
        v-model="fileList"
        :before-read="beforeRead"
        :preview-size="preSize"
        preview-image
        :max-count="1"
      />
    </van-popup>
  </div>
</template>

<script>
export default {
  name: 'EditPhoto',
  props: {
    userPhoto: {
      type: Boolean,
      default: false
    }
  },
  model: {
    prop: 'userPhoto'
  },
  data () {
    return {
      fileList: [],
      preSize: '150px',
      photoId: ''
    }
  },
  methods: {
    onClickRight () {
      this.afterRead()
    },
    // 上传限制
    beforeRead (file) {
      const isImg = file.type === 'image/png' || file.type === 'image/jpeg'
      const limit2m = file.size / 1024 / 1024 < 2
      if (!isImg) {
        this.$toast.fail('请上传png或jpeg格式的图片')
      }
      if (!limit2m) {
        this.$toast.fail('请上传2M内的图片')
      }
      this.photoId = file.lastModified
      return isImg && limit2m
    }
    // 上传方法
  }
}
</script>

<style lang="less" scoped>
.van-popup {
  width: 100%;
  height: 100%;
}
.van-uploader {
  left: 50%;
  margin-left: -150px;
  ::v-deep .van-uploader__upload {
    width: 300px;
    height: 300px;
  }
}
</style>
